package com.sxhuayuan.parking.controller.admin;

import java.math.BigDecimal;
import java.security.interfaces.RSAPublicKey;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.sxhuayuan.parking.compenent.Message;
import com.sxhuayuan.parking.compenent.Page;
import com.sxhuayuan.parking.compenent.web.RespMessage;
import com.sxhuayuan.parking.config.PayStatus;
import com.sxhuayuan.parking.controller.BaseController;
import com.sxhuayuan.parking.dto.OrderListDTO;
import com.sxhuayuan.parking.dto.OrderRefundDTO;
import com.sxhuayuan.parking.entity.Admin;
import com.sxhuayuan.parking.entity.Order;
import com.sxhuayuan.parking.entity.OrderRefund;
import com.sxhuayuan.parking.entity.ParkingIn;
import com.sxhuayuan.parking.plugin.payment.WxPayPlugin;
import com.sxhuayuan.parking.service.AdminService;
import com.sxhuayuan.parking.service.OrderRefundService;
import com.sxhuayuan.parking.service.OrderService;
import com.sxhuayuan.parking.service.ParkingInService;
import com.sxhuayuan.parking.service.QueueMsgSubmitService;
import com.sxhuayuan.parking.service.RSAService;
import com.sxhuayuan.parking.utils.EmojiUtil;
import com.sxhuayuan.parking.utils.SettingUtils;

@RestController("adminOrderController")
@RequestMapping("/admin/order")
public class OrderController extends BaseController {

	@Resource(name = "orderServiceImpl")
	OrderService orderService;
	@Autowired
	ParkingInService inService;
	@Autowired
	QueueMsgSubmitService queueMsgSubmitService;
	@Autowired
	OrderRefundService refundService;
	@Resource(name = "wxPayPlugin")
	WxPayPlugin wxPayPlugin;
	@Autowired
	RSAService rsaService;
	@Resource(name = "adminServiceImpl")
	AdminService adminService;

	/** 分页条件查询订单 */
	@RequestMapping("/list")
	public RespMessage list(@RequestBody OrderListDTO dto) {
		Page<Order> page = orderService.findPage(dto, null);
		return successResp(page);
	}

	/**
	 * 设置订单成功并回调车场
	 * 
	 * @param sn
	 * @return
	 */
	@RequestMapping("/notifyorderpaysuccess")
	public RespMessage notifyOrderPaySuccess(String sn, String huabeiOrder) {
		Order order = orderService.findBySn(sn);
		if (order != null) {
			orderService.paySuccess(order, huabeiOrder);
			return RespMessage.success();
		}
		return RespMessage.error(Message.ORDER_NOT_EXISTS);
	}

	/**
	 * 添加回调车场消息队列，前提是订单必须支付成功
	 * 
	 * @param sn
	 * @return
	 */
	@RequestMapping("/addorderpaysuccessnotice")
	public RespMessage addOrderPaySuccessNotice(String sn) {
		Order order = orderService.findBySn(sn);
		if (order != null && order.getPayStatus() == PayStatus.success) {
			ParkingIn in = inService.findByUniqueId(order.getUniqueId());
			queueMsgSubmitService.submitNotifyParkingLotMsg(in, order);
			return RespMessage.success();
		}
		return RespMessage.error(Message.ORDER_NOT_EXISTS);
	}

	/**
	 * 统计订单数和金额
	 * 
	 * @param dto
	 *            查询条件
	 * @return 返回订单数目和总金额
	 */
	@RequestMapping("/count")
	public RespMessage count(@RequestBody OrderListDTO dto) {
		return successResp(orderService.findCount(dto, null));
	}

	/**
	 * 退款，提交前需要先获取rsa公钥，加密登录密码后提交
	 * 
	 * @param dto
	 * @return
	 */
	@RequestMapping("/refund")
	public RespMessage refund(@RequestBody OrderRefundDTO dto, HttpServletRequest request) {
		Order order = orderService.findBySn(dto.getTradeNo());
		if (order == null || order.getPayStatus() != PayStatus.success) {
			return RespMessage.error("订单不存在或未支付");
		}
		BigDecimal refundMoney = SettingUtils.get().setScale(new BigDecimal(dto.getRefundMoney()));
		if (BigDecimal.ZERO.compareTo(refundMoney) >= 0) {
			return RespMessage.error("退款金额必须大于0！");
		}
		if (order.getPaidMoney().compareTo(refundMoney) < 0) {
			return RespMessage.error("可退款金额不足: " + String.format("%.2f", order.getPaidMoney()));
		}
		Admin admin = adminService.getCurrent();
		// 校验退款密码
		String pswd = rsaService.decrypt(dto.getPswd(), request);
		if (!StringUtils.equals(DigestUtils.md5Hex(pswd), admin.getPassword())) {
			return RespMessage.error("密码错误");
		}
		OrderRefund refund = wxPayPlugin.refund(order, refundMoney, dto.getNote());
		// refundService.refresh(refund, LockModeType.PESSIMISTIC_READ);
		if (refund.getIsSuccess()) {
			return RespMessage.success("退款成功");
		} else {
			return RespMessage.error("退款失败: " + refund.getError());
		}
	}

	/**
	 * 获取公钥
	 * 
	 * @param request
	 *            req
	 * @return 公钥字符串
	 */
	@RequestMapping("/refund/rsa")
	public RespMessage getRsa(HttpServletRequest request) {
		RSAPublicKey publicKey = rsaService.generateKey(request);
		String s = new String(Base64.encodeBase64(publicKey.getEncoded()));
		return successResp(s);
	}
}
